﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Threading;

namespace Taste.Demos.Silverlight.DataModel
{
    public class CustomerContext
    {
        private IEnumerable<Customer> _customers;
        private DispatcherTimer _delayTimer;
        private Action _delayedAction;

        public CustomerContext()
        {
            _delayTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
            _delayTimer.Tick += new EventHandler(OnDelayTimerTick);

            _customers = new [] {
                new Customer { FirstName = "Eric", LastName = "Duchamp" },
                new Customer { FirstName = "Tom", LastName = "Bauer" },
                new Customer { FirstName = "Anna", LastName = "Tippin" }
            };
        }

        public void LoadCustomers(Action<IEnumerable<Customer>> callback)
        {
            // let's pretend this takes a while
            _delayedAction = () => callback(_customers);
            _delayTimer.Start();
        }

        public void SaveCustomers(IEnumerable<Customer> customers, Action callback)
        {
            _delayedAction = () =>
            {
                _customers = customers.ToArray();
                callback();
            };
            _delayTimer.Start();
        }

        private void OnDelayTimerTick(object sender, EventArgs e)
        {
            _delayTimer.Stop();
            if(_delayedAction != null)
                _delayedAction();
        }
    }
}
